package com.huajx.jrb.controller;

import com.huajx.core.annotation.Route;
import com.huajx.core.common.Columns;
import com.huajx.core.handler.Controller;
import com.huajx.jrb.model.Archive;
import com.huajx.jrb.model.Borrow;
import com.huajx.jrb.service.ArchiveService;
import com.huajx.jrb.service.BorrowService;
import com.huajx.util.StrUtil;
import com.huajx.util.convert.Convert;

import java.util.Date;

@Route(controllerKey = "/borrow")
public class BorrowController extends Controller {
    public void index() {
        int ps = getParaToInt("ps", 10);
        int pi = getParaToInt("pi", 0);

        String lender = getPara("lender");
        String title = getPara("title");
        String archiveId = getPara("archiveId");

        Columns columns = new Columns();

        if (StrUtil.isNotBlank(lender)) {
            columns.like("lender", lender);
        }

        if (StrUtil.isNotBlank(archiveId)) {
            columns.eq("archiveId", archiveId);
        }

        if (StrUtil.isNotBlank(title)) {
            columns.like("title&code&no", title);
        }

        renderJson(BorrowService.service.paginate(columns, pi, ps));
    }

    public void record() {
        Long archiveId = Convert.toLong(getPara());
        Borrow borrow = BorrowService.service.findLastedByArchiveId(archiveId);
        renderJson(borrow);
    }

    public void edit() {
        Long id = getParaToLong("id");
        if (id == null) {
            renderJson(new Borrow());
        } else {
            renderJson(BorrowService.service.findById(id));
        }
    }

    public void delete() {
        BorrowService.service.delete(getParaToLong("id"));
        renderJsonSuccess();
    }

    public void save() {
        Borrow borrow = getModel(Borrow.class);

        boolean isAdd = borrow.getId() == null || borrow.getId().equals(0L);
        if (isAdd) {
            borrow.setCreateAt(new Date());
            BorrowService.service.save(borrow);
        } else {
            BorrowService.service.update(borrow);
        }

        String status = borrow.getStatus();
        if ("借出".equals(status)) {
            Archive archive = ArchiveService.service.findById(borrow.getArchiveId());
            archive.setStatus(status);
            archive.setLender(borrow.getLender());
            archive.setLenderAt(borrow.getLenderAt());
            ArchiveService.service.update(archive);
        } else {
            Archive archive = ArchiveService.service.findById(borrow.getArchiveId());
            archive.setStatus("在库");
            archive.setLender(null);
            archive.setLenderAt(null);
            ArchiveService.service.update(archive);
        }

        renderJsonSuccess();
    }
}
